package com.medical.feign.config;

import cn.dev33.satoken.same.SaSameUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.medical.feign.decoder.FeignDecoder;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.optionals.OptionalDecoder;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {

    /**
     *  定义解码器，解码响应结构
     */
    @Bean
    public Decoder feignDecoder(ObjectProvider<HttpMessageConverters> messageConverters) {
        return new OptionalDecoder((new ResponseEntityDecoder(new FeignDecoder(new SpringDecoder(messageConverters)))));
    }

    /**
     *  feign 拦截器，在feign请求发出前，加入一些操作
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            requestTemplate.header(SaSameUtil.SAME_TOKEN, SaSameUtil.getToken());
            //如果希望被调用方法有会话状态的话，此处旧还需要将satoken添加到请求头中
            requestTemplate.header(StpUtil.getTokenName(), StpUtil.getTokenValue());
        };
    }
}
